//
//  WBStatusPictureView.swift
//  TYCWeiBo
//
//  Created by 中发 on 2018/6/12.
//  Copyright © 2018年 中发. All rights reserved.
//

import UIKit

class WBStatusPictureView: UIView {

    var viewModel: WBStatusViewModel? {
        
        didSet{
            calcViewSize()
        }
    }
    
    /// 根据视图模型大小，调整视图显示内容
    private func calcViewSize() {
        //处理宽度
        //1.单图，根据配图视图的大小，修改subviews[0]的高度
        if viewModel?.picURLs?.count == 1 {
            let viewSize = viewModel?.pictureViewSize ?? CGSize()
            //获取第0个图像视图
            let v = subviews[0]
            v.frame = CGRect(x: 0, y: WBStatusViewOutterMargin, width: viewSize.width, height: viewSize.height - WBStatusViewOutterMargin)
        }else {
            //多图（无图），恢复subviews[0]的高度，保证九宫格的完整
            let v = subviews[0]
            v.frame = CGRect(x: 0, y: WBStatusViewOutterMargin, width: WBStatusViewItemWidth, height: WBStatusViewItemWidth) 
        }
        ///修改高度约束
        heightCons.constant = viewModel?.pictureViewSize.height ?? 0
    }
    
    
    /// 配图视图的数组
    var urls: [WBStatusPicture]?{
        didSet {
            //1.隐藏所有的imageView
            for v in subviews {
                v.isHidden = true
            }
            //2.遍历URL数组，顺序设置图像
            var index = 0
            
            for url in urls ?? [] {
                /// 获得对应索引的imageView
                let iv = subviews[index] as! UIImageView
                //4张图像处理
                if index == 1 && urls?.count == 4{
                    index += 1
                }
                //设置图像
                iv.tempSetImage(urlString: url.thumbnail_pic, placeholderImage: nil)
                //显示图像
                iv.isHidden = false
                index += 1
            }
        }
    }
    
    
    @IBOutlet weak var heightCons: NSLayoutConstraint!

    override func awakeFromNib() {
        setUpUI()
    }
}

// MARK: - 设置界面
extension WBStatusPictureView {
    
    /// cell中所有控件都是提前准备好
    //  设置的时候，根据数据决定是否显示
    //  不要动态创建控件
    private func setUpUI() {
        backgroundColor = superview?.backgroundColor
        /// 超出边界内容不显示
        clipsToBounds = true
        let count = 9
        let rect = CGRect(x: 0, y: WBStatusViewOutterMargin, width: WBStatusViewItemWidth, height: WBStatusViewItemWidth)

        for i in 0..<count {
            let iv = UIImageView()
            iv.contentMode = .scaleAspectFill
            iv.clipsToBounds = true
            iv.backgroundColor = UIColor.red
            /// 行--y
            let  row = CGFloat(i / count)
            /// 列--x
            let  col = CGFloat(i % count)
            let xOffSet = col * (WBStatusViewItemWidth + WBStatusViewInnerMargin)
            let yOffSet = row * (WBStatusViewItemWidth + WBStatusViewInnerMargin)
            iv.frame = rect.offsetBy(dx: xOffSet, dy: yOffSet)
            addSubview(iv)
            
        }
    }
}
